package com.studymaster.dao.impl;

import java.io.ByteArrayOutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.jivesoftware.smack.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.studymaster.dao.User_DetailDao;
import com.studymaster.domain.User;
import com.studymaster.domain.User_Detail;

@Repository
public class User_DetailDaoImpl implements User_DetailDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	protected RowMapper user_DetailRowMap = new RowMapper() {
		@Override
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			User_Detail mUser_Detail = new User_Detail();
			
			mUser_Detail.setUser_id(rs.getString("user_id"));
			mUser_Detail.setUsername(rs.getString("username"));
			mUser_Detail.setPicture(rs.getString("picture"));
			mUser_Detail.setPicdate(rs.getString("picdate"));		
			return mUser_Detail;
		}
	};
	
	
	@Override
	public boolean UpdateHeadIcon(String mStudentid, String mHeadIcon) {
		// TODO Auto-generated method stub
		try {

			String updatesql = "update user_detail set  picture = ?,picdate = ? where user_id = ?";
			return jdbcTemplate.update(updatesql, 
					new Object[]{mHeadIcon,String.valueOf(System.currentTimeMillis()),mStudentid},
					new int[] {java.sql.Types.VARCHAR,java.sql.Types.VARCHAR,java.sql.Types.VARCHAR})>0;
			
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}

	}
    //有新头像则返回mPictureAndPicdate,若没有新头像则返回"";
	@Override
	public String DownLoadNewHeadIcon(String mStudentid,String mPicdate) {
		// TODO Auto-generated method stub
		try {
			User_Detail mUser_Detail = null;
			if(mPicdate.equals("0")){ //手机本地无该用户头像和头像时间，就直接下载。
				String searchSql = "select * from user_detail where user_id = ?";
				System.out.println(searchSql);
			    mUser_Detail =(User_Detail) jdbcTemplate.queryForObject(searchSql, new Object[] { mStudentid }
			    ,user_DetailRowMap);
			}else{//若服务器的时间比本地头像的时间晚，则认为有新头像，返回头像和时间
				String searchSql = "select * from user_detail where user_id = ? and picdate > ?";
				System.out.println(searchSql);
				mUser_Detail = (User_Detail)jdbcTemplate.queryForObject(searchSql, new Object[] { mStudentid, mPicdate }
			    ,user_DetailRowMap);
			}
		    if(mUser_Detail != null){
		    	String mPictureAndPicdate = mUser_Detail.getPicture() +","+ mUser_Detail.getPicdate();
		    	return mPictureAndPicdate;
		    }else{
		    	return "";
		    }
		} catch (Exception e) {
			// TODO: handle exception
			return "";
		}

		 
	}

}
